package com.dirven.game;

import com.badlogic.gdx.InputProcessor;
import com.dirven.game.sprite.GridSprite;
import com.dirven.game.sprite.Player;

public class InputManager implements InputProcessor {

	private int touchDownX,
				touchDownY,
				touchDownPointer;

	private boolean isDragging = false;
	
	private Player player;
	
	public InputManager(Player player) {
		this.player = player;
	}
	
	public void reset() {
		touchDownX = -1;
		touchDownY = -1;
		touchDownPointer = -1;
		isDragging = false;
	}
	
	public void setPlayer(Player player) {
		this.player = player;
	}
	
	@Override
	public boolean keyDown(int arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean keyTyped(char arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean keyUp(int arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean scrolled(int arg0) {
		//Gdx.app.log("DIRVEN", "scrolled");
		return false;
	}

	@Override
	public boolean touchDown(int x, int y, int pointer, int button) {
		touchDownX = x;
		touchDownY = y;
		touchDownPointer = pointer;
		
		return false;
	}

	@Override
	public boolean touchDragged(int x, int y, int pointer) {
		
		if(isDragging == false && pointer == touchDownPointer) {
			isDragging = true;
		}
		return false;
	}

	@Override
	public boolean touchMoved(int arg0, int arg1) {
		//Gdx.app.log("DIRVEN", "touch moved");
		return false;
	}

	@Override
	public boolean touchUp(int x, int y, int pointer, int button) {
		
		if(isDragging && pointer == touchDownPointer) {
			
			int resultantX = touchDownX - x;
			int resultantY = touchDownY - y;
			
			// If magnitude of swipe in x direction is greater than the magnitude of y direction,
			// then it either swiped left or right
			if(Math.abs(resultantX) > Math.abs(resultantY)) {
				
				if(resultantX > 0) {
					player.setDirection(GridSprite.DIRECTION_WEST);
				} else {
					player.setDirection(GridSprite.DIRECTION_EAST);
				}
				
			// If magnitude of swipe in y direction is greater than the magnitude of x direction,
			// then it either swiped up or down
			} else {
				if(resultantY > 0) {
					player.setDirection(GridSprite.DIRECTION_NORTH);
				} else {
					player.setDirection(GridSprite.DIRECTION_SOUTH);
				}
			}
			
			// No longer dragging
			isDragging = false;
		}
		
		return false;
	}
	
}
